package com.ljc.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljc.dto.Result;
import com.ljc.entity.ShopType;
import com.ljc.mapper.ShopTypeMapper;
import com.ljc.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.ljc.utils.RedisConstants.LIST_SHOP_KEY;
import static com.ljc.utils.RedisConstants.LIST_SHOP_TTL;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getList() {
        //1、从redis查询商铺列表缓存
        String key = LIST_SHOP_KEY;
        String listJson = stringRedisTemplate.opsForValue().get(key);
        //2、存在直接返回
        if (StrUtil.isNotBlank(listJson)) {
            List<ShopType> list = JSONUtil.toList(listJson, ShopType.class);
            return Result.ok(list);
        }
        //3、不存在，从数据库中读取
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //4、并将结果保存到redis中
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(typeList));
        stringRedisTemplate.expire(key, LIST_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(typeList);
    }
}
